package org.example;

import net.sf.json.JSONObject;
import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class CamundaWorker {
    private final static Logger LOGGER = Logger.getLogger(CamundaWorker.class.getName());

    public static void main(String[] args) {
        ExternalTaskClient client = ExternalTaskClient.create()
                .baseUrl("http://localhost:8080/engine-rest")
                .asyncResponseTimeout(10000) // 长轮询超时时间
                .build();

        // 订阅外部任务topic
        client.subscribe("addEvent")//监听Camunda引擎的指定任务Topic
                .lockDuration(1000)
                .handler((externalTask, externalTaskService) -> {
                    //从监听到的任务中获取变量a,b（工作流该任务之前的其他任务产生的变量）
                    Long a = (Long) externalTask.getVariable("a");
                    Long b = (Long) externalTask.getVariable("b");

                    //调用通用API，先新建一个参数Map，传入需要传递的参数
                    Map params = new HashMap();
                    params.put("a", a);
                    params.put("b", b);

                    //APIConnector承担了查询云端API的工作，传入参数Map发起查询，返回JSON对象
                    JSONObject result = APIConnector.query("add", params);
                    //查询API文档，发现返回结果中“res”存放计算结果，但由于该API仅完成整数运算，所以需要进行适配
                    int result_value = (int) result.get("res");


                    //放回到变量Map中
                    VariableMap variableMap = Variables.createVariables()
                            .putValue("result", result_value);
                    LOGGER.info("add " + a + " and " + b);


                    externalTaskService.complete(externalTask, variableMap);

                })
                .open();

        client.subscribe("subEvent")
                .lockDuration(1000)
                .handler((externalTask, externalTaskService) -> {
                    Long a = (Long) externalTask.getVariable("a");
                    Long b = (Long) externalTask.getVariable("b");
                    Map params = new HashMap();
                    params.put("a", a);
                    params.put("b", b);

                    JSONObject result = APIConnector.query("sub", params);


                    VariableMap variableMap = Variables.createVariables()
                            .putValue("result", result.get("res"));
                    LOGGER.info("sub " + a + " with " + b);


                    // Complete the task

                    externalTaskService.complete(externalTask, variableMap);

                })
                .open();

        client.subscribe("mulEvent")
                .lockDuration(1000)
                .handler((externalTask, externalTaskService) -> {
                    Long a = (Long) externalTask.getVariable("a");
                    Long b = (Long) externalTask.getVariable("b");
                    Map params = new HashMap();
                    params.put("a", a);
                    params.put("b", b);

                    JSONObject result = APIConnector.query("mul", params);

                    VariableMap variableMap = Variables.createVariables()
                            .putValue("result", result.get("res"));
                    LOGGER.info("multi " + a + " and " + b);


                    externalTaskService.complete(externalTask, variableMap);

                })
                .open();
        client.subscribe("weatherEvent")
                .lockDuration(1000)
                .handler((externalTask, externalTaskService) -> {
                    String city = externalTask.getVariable("city");
                    Map params = new HashMap();
                    params.put("city", city);

                    JSONObject result = APIConnector.query("weather", params);
                    int temp1 = Integer.parseInt((String) result.get("temp1"));
                    int temp2 = Integer.parseInt((String) result.get("temp2"));
                    int temp = (temp1 + temp2) / 2;
                    String weather = (String) result.get("weather");
                    int window = 1;
                    if (weather.contains("雨")) {
                        window = 0;
                    }
                    System.out.println(weather);

                    VariableMap variableMap = Variables.createVariables()
                            .putValue("temp", temp)
                            .putValue("window", window);
                    LOGGER.info("temp: "+temp+" window: "+window );


                    externalTaskService.complete(externalTask, variableMap);

                })
                .open();
        client.subscribe("windowEvent")
                .lockDuration(1000)
                .handler((externalTask, externalTaskService) -> {
                    String id = externalTask.getVariable("id");
                    int open1 = externalTask.getVariable("open");
                    boolean open2 = false;
                    if (open1 == 1) {
                        open2 = true;
                    }
                    Map params = new HashMap();
                    params.put("id", id);
                    params.put("open", open2);

                    JSONObject result = APIConnector.query("setWindow", params);
                    Boolean open = (Boolean) result.get("open");
                    String window = "关闭";
                    if (open) {
                        window = "开启";
                    }
                    VariableMap variableMap = Variables.createVariables()
                            .putValue("result", window);
                    LOGGER.info("id: " + id+" open: " + open);


                    externalTaskService.complete(externalTask, variableMap);

                })
                .open();
        client.subscribe("tempEvent")
                .lockDuration(1000)
                .handler((externalTask, externalTaskService) -> {
                    String id = externalTask.getVariable("id");
                    int temp = Integer.parseInt(externalTask.getVariable("temp"));
                    Map params = new HashMap();
                    params.put("id", id);
                    params.put("temp", temp);

                    JSONObject result = APIConnector.query("setTemp", params);

                    VariableMap variableMap = Variables.createVariables()
                            .putValue("result", result.get("temp"));
                    LOGGER.info("id: " + id+" temp: " + temp);


                    externalTaskService.complete(externalTask, variableMap);

                })
                .open();
    }
}
